import 'dart:async';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:location_test/app/presentation/controllers/home_controller.dart';
import 'package:nmea_plugin/nmea_models.dart';

class NmeaLogController extends GetxController {
  // --- 数据源 ---
  late final RxList<NmeaMessage> _nmeaHistorySource;
  StreamSubscription? _nmeaSubscription;

  // --- 实时状态摘要 ---
  final fixStatus = '未定位'.obs;
  final fixStatusColor = Colors.red.obs;
  final satellitesInUse = 0.obs;
  final satellitesInView = 0.obs;
  final hdop = 0.0.obs;
  final vdop = 0.0.obs;

  // --- 统计数据 ---
  final messageCounts = <String, int>{}.obs;
  final activeSatellitePRNs = <int>[].obs;
  final visibleSatellites = <SatelliteInfo>[].obs; // [修正] 使用正确的类型 SatelliteInfo

  // 临时存储分多条发送的GSV报文
  final _tempVisibleSatellites = <SatelliteInfo>[]; // [修正] 使用正确的类型 SatelliteInfo

  @override
  void onInit() {
    super.onInit();
    if (Get.isRegistered<HomeController>()) {
      _nmeaHistorySource = Get.find<HomeController>().nmeaHistory;
      _nmeaSubscription = _nmeaHistorySource.listen(_onNmeaDataChanged);
      _processFullHistory();
    } else {
      _nmeaHistorySource = <NmeaMessage>[].obs;
    }
  }

  void _onNmeaDataChanged(List<NmeaMessage> history) {
    if (history.isNotEmpty) {
      _processNewMessage(history.first);
    }
  }

  void _processFullHistory() {
    for (final message in _nmeaHistorySource.reversed) {
      _processNewMessage(message);
    }
  }

  void _processNewMessage(NmeaMessage message) {
    messageCounts.update(message.sentenceType, (value) => value + 1, ifAbsent: () => 1);

    if (message is GgaMessage) {
      satellitesInUse.value = message.numberOfSatellites ?? 0;
      _updateFixStatus(message.fixQuality);
    } else if (message is GsaMessage) {
      hdop.value = message.hdop ?? 0.0;
      vdop.value = message.vdop ?? 0.0;
      // [修正] 使用正确的属性名 prnNumbers
      activeSatellitePRNs.value = message.prnNumbers.where((prn) => prn > 0).toList();
    } else if (message is GsvMessage) {
      if (message.messageNumber == 1) {
        _tempVisibleSatellites.clear();
        satellitesInView.value = message.satellitesInView;
      }
      
      _tempVisibleSatellites.addAll(message.satellites);

      if (message.messageNumber == message.totalMessages) {
        _tempVisibleSatellites.sort((a, b) => a.prn.compareTo(b.prn));
        visibleSatellites.value = List.from(_tempVisibleSatellites);
      }
    }
  }

  void _updateFixStatus(int? quality) {
    switch (quality) {
      case 0:
        fixStatus.value = '未定位';
        fixStatusColor.value = Colors.red;
        break;
      case 1:
        fixStatus.value = 'GPS 单点定位';
        fixStatusColor.value = Colors.orange;
        break;
      case 2:
        fixStatus.value = '差分 GPS';
        fixStatusColor.value = Colors.green;
        break;
      case 4:
        fixStatus.value = 'RTK 固定解';
        fixStatusColor.value = Colors.teal;
        break;
      case 5:
        fixStatus.value = 'RTK 浮点解';
        fixStatusColor.value = Colors.cyan;
        break;
      default:
        fixStatus.value = '未知状态 ($quality)';
        fixStatusColor.value = Colors.grey;
    }
  }

  void clearHistory() {
    if (Get.isRegistered<HomeController>()) {
      Get.find<HomeController>().nmeaHistory.clear();
    }
    fixStatus.value = '未定位';
    fixStatusColor.value = Colors.red;
    satellitesInUse.value = 0;
    satellitesInView.value = 0;
    hdop.value = 0.0;
    vdop.value = 0.0;
    messageCounts.clear();
    activeSatellitePRNs.clear();
    visibleSatellites.clear();
    _tempVisibleSatellites.clear();
  }

  @override
  void onClose() {
    _nmeaSubscription?.cancel();
    super.onClose();
  }
}
